package com.hotel.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.hotel.bean.Department;
import com.hotel.bean.RespBean;
import com.hotel.exception.SteduException;
import com.hotel.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/dept")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @PostMapping
    public RespBean insert(@RequestBody @Validated Department department) throws SteduException {
        if (deptService.insert(department)) {
            return RespBean.ok("添加成功");
        }
        return RespBean.error("添加失败");
    }
    @DeleteMapping("/{did}")
    public RespBean delete(@PathVariable Integer did) throws SteduException {
        if (deptService.delete(did)) {
            return RespBean.ok("删除成功");
        }
        return RespBean.error("删除失败");
    }
    @PutMapping
    public RespBean update(@RequestBody @Validated Department department) throws SteduException {
        if (deptService.update(department)) {
            return RespBean.ok("修改成功");
        }
        return RespBean.error("修改失败");
    }
    @GetMapping
    public RespBean selectAll(){
        if(deptService.selectAll() != null){
            return RespBean.ok("",deptService.selectAll());
        }
        return RespBean.error("出错");
    }
    @GetMapping("/{did}")
    public RespBean selectByEid(@PathVariable Integer did){
        if(deptService.selectByDid(did) != null){
            return RespBean.ok("",deptService.selectByDid(did));
        }
        return RespBean.error("出错");
    }
    @PostMapping("/upload")
    public RespBean upload(MultipartFile file) throws IOException, SteduException {
        List<Department> departmentList = ExcelUtil.getReader(file.getInputStream()).readAll(Department.class);
        if(!CollectionUtil.isEmpty(departmentList)){
            for(Department dept : departmentList){
                try {
                    deptService.insert(dept);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return RespBean.ok("");
    }
}
